package com.liqi.frame.comm.aop;

import com.liqi.frame.comm.token.TokenUtil;
import com.liqi.frame.comm.util.ConfUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Aspect
@Component
public class FormPageAspect {
    @Value("${app.projectName}")
    private String projectName;
    @Value("${app.indexPage}")
    private String indexPage;
    @Value("${app.ssoLogout}")
    private String ssoLogout;
    @Value("${app.fileServerPath}")
    private String fileServerPath;

//    Logger logger= LoggerFactory.getLogger(FormPageAspect.class);
    @Pointcut("@annotation(com.liqi.frame.comm.aop.FormPage)")
    protected void annotation_FullPage(){};

    @Pointcut("within(com.liqi.frame..*)||within(com.liqi.biz..*)")
    protected void webController(){};

    @AfterReturning(pointcut="webController() && annotation_FullPage()",returning="result")
    public void afterReturning_AppIndex(JoinPoint jp, Object result) {
        adjustPageLayout(jp,result);
    }

    public void setLayoutKey(String layoutKey) {
        this.layoutKey = layoutKey;
        this.layoutKeyMenu=layoutKey+"MenuDto";
        this.layoutKeySubMenu=layoutKey+"SubMenu";
        this.layoutKeyPrev=layoutKey+"Prev";
    }

    private String layoutKey="form";
    private String layoutKeyPrev="layoutPrev";
    //主菜单
    private String layoutKeyMenu="layoutMenu";
    //子菜单
    private String layoutKeySubMenu="layoutSubMenu";

    private String layoutKeyUsername = "layoutUsername";
    // js版本号
    private String jsVersion = "jsVersion";
    // 文件路径
//    private String fileServerPath = "fileServerPath";
    // 项目中文名称
//    private String projectName = "projectName";
    // 项目发布名
    private String contextPath = "contextPath";
    // sso的登出路径
//    private String ssoLogout = "ssoLogout";
    // 首页地址
//    private String indexPage = "indexPage";

    private void adjustPageLayout(JoinPoint jp, Object result){
        Signature jpsignature= jp.getSignature();
        Object[] args= jp.getArgs();
        HttpServletRequest request=null;
        for(Object arg:args){
            if(arg ==null)continue;
            if( HttpServletRequest.class.isAssignableFrom(arg.getClass())){
                request= (HttpServletRequest)arg;
                break;
            }
        }
        if(request!=null && jpsignature instanceof MethodSignature){
            MethodSignature  signature=(MethodSignature)jpsignature;
            FormPage annoFormPage=  AnnotationUtils.findAnnotation(signature.getMethod(), FormPage.class);
            RequestMapping qequestMapping=  AnnotationUtils.findAnnotation(signature.getMethod(), RequestMapping.class);
            String[] paths=qequestMapping.path();
            String router=annoFormPage.router();
            //需要知道是否从 特定URL来的
            boolean isMatched=false;
            int matchLimit=3;
            for(String path:paths){
                int idx= path.indexOf(router);
                if(  idx>=0 && idx<=1){
                    if(request.getRequestURI().indexOf( path)>0){
                        //是当前路径
                        isMatched=true;
                        break;
                    }
                    if(--matchLimit<0 ){
                        break;
                    }
                }
            }
            if(isMatched){
                if(result instanceof ModelAndView){
                    ModelAndView mvcData=(ModelAndView)result;
                    String contentViewName = mvcData.getViewName();
                    mvcData.setViewName("comm/form");
                    String prevLayout=(String)mvcData.getModelMap().get(layoutKey);
                    ModelMap datamap= mvcData.getModelMap();
                    datamap.put("screen_content",contentViewName+".html");
                    datamap.put(layoutKey, annoFormPage.layout());
                    datamap.put(layoutKeyMenu,annoFormPage.menu());
//                    datamap.put(layoutKeySubMenu,annoFormPage.subMenu());
                    datamap.put(layoutKeyPrev,prevLayout );
                    datamap.put(layoutKeyUsername, TokenUtil.getFullname());
                    String jsVersionConf = ConfUtil.getConf("jsVersion");
                    if (jsVersionConf!=null && !Objects.equals("",jsVersionConf)) {
                        datamap.put(jsVersion, jsVersionConf);
                    } else {
                        datamap.put(jsVersion, "20200320");
                    }
//                    String fileServerPathConf = ConfUtil.getConf("fileServerPath");
//                    if (fileServerPathConf!=null && !"".equals(fileServerPathConf)) {
//                        datamap.put(fileServerPath, fileServerPathConf);
//                    }
//                    datamap.put("fileServerPath", fileServerPath);

                    datamap.put("projectName", projectName);
                    String ssoLogoutConf = ConfUtil.getConf("sso.logout");
                    if (ssoLogoutConf!=null && !"".equals(ssoLogoutConf)) {
                        datamap.put(ssoLogout, ssoLogoutConf);
                    }

                    String contextPath = request.getServletContext().getContextPath();
                    datamap.put(this.contextPath, contextPath);
                }
            }
        }
    }
}
